/**
 * Created with PyCharm.
 * User: xiaowei
 * Date: 14-8-20
 * Time: 下午5:58
 * To change this template use File | Settings | File Templates.
 */
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("esri.map");
dojo.require("esri.layers.agstiled");
dojo.require("esri.toolbars.draw");
dojo.require("dijit.dijit"); // optimize: load dijit layer
dojo.require("esri.undoManager");
dojo.provide("myModules.customoperation");

var mymap,toolbar,reExtent,boundary_List,undoManager,resizeTimer;

//撤销 重做 申明
dojo.declare("myModules.customoperation.Add", esri.OperationBase, {
    label: "Add Graphic",
    constructor: function ( /*graphicsLayer, addedGraphic*/ params) {
        params = params || {};
        if (!params.graphicsLayer) {
            console.error("graphicsLayer is not provided");
            return;
        }
        this.graphicsLayer = params.graphicsLayer;

        if (!params.addedGraphic) {
            console.error("no graphics provided");
            return;
        }
        this._addedGraphic = params.addedGraphic;
    },

    performUndo: function () {
        this.graphicsLayer.remove(this._addedGraphic);
    },

    performRedo: function () {
        this.graphicsLayer.add(this._addedGraphic);
    }
});
//初始化地图
function init(){
    undoManager = new esri.UndoManager();
    mymap = new esri.Map("map");
    //加载天地图
    dojo.declare("TianDiTiledMapServiceLayer", esri.layers.TiledMapServiceLayer, {
        constructor: function() {
            this.spatialReference = new esri.SpatialReference({ wkid:4326 });
            this.initialExtent = (this.fullExtent =
                new esri.geometry.Extent(-180.0, -90.0, 180.0, 90.0, this.spatialReference));
            this.tileInfo = new esri.layers.TileInfo({
                "rows" : 256,
                "cols" : 256,
                "compressionQuality" : 0,
                "origin" : { "x" : -180,"y" : 90},
                "spatialReference" : {"wkid" : 4326},
                "lods" : [
                    {"level" : 0, "resolution" : 0.703125, "scale" : 295497593.05875},
                    {"level" : 1, "resolution" : 0.3515625, "scale" : 147748796.529375},
                    {"level" : 2, "resolution" : 0.17578125, "scale" : 73874398.264688},
                    {"level" : 3, "resolution" : 0.087890625, "scale" : 36937199.132344},
                    {"level" : 4, "resolution" : 0.0439453125, "scale" : 18468599.566172},
                    {"level" : 5, "resolution" : 0.02197265625, "scale" : 9234299.783086},
                    {"level" : 6, "resolution" : 0.010986328125, "scale" : 4617149.891543},
                    {"level" : 7, "resolution" : 0.0054931640625, "scale" : 2308574.945771},
                    {"level" : 8, "resolution" : 0.00274658203125, "scale" : 1154287.472886},
                    {"level" : 9, "resolution" : 0.001373291015625, "scale" : 577143.736443},
                    {"level" : 10, "resolution" : 0.0006866455078125, "scale" : 288571.86822143558},
                    {"level" : 11, "resolution" : 0.00034332275390625, "scale" : 144285.93411071779},
                    {"level" : 12, "resolution" : 0.000171661376953125, "scale" : 72142.967055358895},
                    {"level" : 13, "resolution" : 8.58306884765625e-005, "scale" : 36071.483527679447},
                    {"level" : 14, "resolution" : 4.291534423828125e-005, "scale" : 18035.741763839724},
                    {"level" : 15, "resolution" : 2.1457672119140625e-005, "scale" : 9017.8708819198619},
                    {"level" : 16, "resolution" : 1.0728836059570313e-005, "scale" : 4508.9354409599309},
                    {"level" : 17, "resolution" : 5.3644180297851563e-006, "scale" : 2254.4677204799655}]
            });
            this.loaded = true;
            this.onLoad(this);
        },
        getTileUrl: function(level, row, col) {
            var levelMap = "";
            if(level<10){
                levelMap = "A0512_EMap";
            }else if(level<12){
                levelMap = "B0627_EMap1112";
            }else if(level<18){
                levelMap = "siwei0608";
            }
            return "http://t1.tianditu.cn/DataServer?T=vec_c&"+levelMap+"&X=" + col + "&Y=" + row + "&L=" + (level*1+1);
        }
    });
    //文字标注
    dojo.declare("TianDiBiaoZhuMapServiceLayer", TianDiTiledMapServiceLayer, {
        getTileUrl: function(level, row, col) {
            return "http://t1.tianditu.cn/DataServer?T=cva_c&X=" + col + "&Y=" + row + "&L=" + (level*1+1);
        }
    });
    //影像地图
    dojo.declare("TianDiYXMapServiceLayer", TianDiTiledMapServiceLayer, {
        getTileUrl: function(level, row, col) {//wmts
            return "http://t1.tianditu.cn/DataServer?T=img_c&X=" + col + "&Y=" + row + "&L=" + (level*1+1);
        }
    });
    //加载天地图结束
    dojo.connect(mymap, 'onLoad', function(theMap) {
        //resize the map when the browser resizes
        dojo.connect(dijit.byId('map'), 'resize', map,map.resize);
    });

    dojo.connect(mymap, "onLoad", createToolbar);
    //dojo.connect(mymap, "onLoad",loadWaterPoint );
    // dojo.connect(mymap, "onLoad",eval(load_type) );
    // dojo.connect(mymap, "onLoad",loadParkRange);
    dojo.connect(mymap, "onExtentChange", showExtent);  //

    esri.config.defaults.map.panDuration = 1000; //time in milliseconds; default panDuration:250
    esri.config.defaults.map.panRate = 50; //refresh rate of zoom animation; default panRate:25

    mymap.addLayer(new TianDiTiledMapServiceLayer());
    mymap.addLayer(new TianDiYXMapServiceLayer());
    mymap.addLayer(new TianDiBiaoZhuMapServiceLayer());
    mymap.resize();
    mymap.reposition();
    var point=$("#rangePoint").attr("xmin");
    var xmin=parseFloat($("#rangePoint").attr("xmin"));
    var ymin=parseFloat($("#rangePoint").attr("ymin"));
    var xmax=parseFloat($("#rangePoint").attr("xmax"));
    var ymax=parseFloat($("#rangePoint").attr("ymax"));
    if(point){
        reExtent = new esri.geometry.Extent({"xmin":xmin,"ymin":ymin,"xmax":xmax,"ymax":ymax,"spatialReference":{"wkid":102100}});
    }else
        reExtent = new esri.geometry.Extent({"xmin":118.754667,"ymin":32.170577,"xmax":118.98104,"ymax":32.219344,"spatialReference":{"wkid":102100}});
    mymap.setExtent(reExtent);//区域范围
}
dojo.addOnLoad(init);//调用init
//init();
function createToolbar(themap) {
    //resize the map when the browser resizes
    dojo.connect(dijit.byId('map'), 'resize', mymap,mymap.resize);
    toolbar = new esri.toolbars.Draw(mymap);
    dojo.connect(toolbar, "onDrawEnd", addToMap);
}

var dotList=new Array();
function drowWaterPoint(){
    toolbar.activate(esri.toolbars.Draw.POINT);
    var info="开始标注水源地信息";
}

function drowTransline(){
    toolbar.activate(esri.toolbars.Draw.FREEHAND_POLYLINE);
    var info="开始标注化学运输品路线";
    infoPop(info);
}

function infoPop(info){
    $("#toast-container").remove();
    var opts = {
        "closeButton": true,
        "debug": false,
        "positionClass": "toast-top-right",
        "onclick": null,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": "2000",
        "extendedTimeOut": "5000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };
    toastr.info("", info, opts);
    console.log(info)

}
//drawing
function addToMap(geometry) {
    toolbar.deactivate();
    mymap.showZoomSlider();
   
    switch (geometry.type) {
        case "point":
            var url='/static/images/marker_p.png';
            var symbol=new esri.symbol.PictureMarkerSymbol(url, 24, 24);
             $(productPer).find('.geo_x').val(geometry.x);
             $(productPer).find('.geo_y').val(geometry.y);
            break;

        case "polyline":
            var url='/static/images/line.png';
            var symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0,186,207]), 3);

            break;
    }

    mymap.graphics.clear();
    var graphic = new esri.Graphic(geometry, symbol);
    mymap.graphics.add(graphic);

    switch (geometry.type) {
        case "point":
            dotList=graphic.geometry;
            var x=dotList.x;
            var y=dotList.y;
            $('#waterSourceName').attr('x',x);
            $('#waterSourceName').attr('y',y);
            break;
        case "polyline":
            values = JSON.stringify(graphic.geometry.paths[0]);
            $('#waterSourceName').attr('polyline',values)
            break;
    }

    var operation = new myModules.customoperation.Add({
        graphicsLayer: mymap.graphics,
        addedGraphic: graphic
    });

    undoManager.add(operation);
    mymap.graphics.add(graphic);
}

function toSubmitWaterPoint(){
    var title="提交水源地信息";
    var content=$("#waterCommitDiv").html();
    var type='WaterSource';
    toSubmitModal(title,content,type);
    $('#Modal').modal({show:true});
}

function toSubmitTransline(){
    var title="提交运输路线信息";
    var content=$("#waterCommitDiv").html();
    var type='Transline';
    toSubmitModal(title,content,type);
    $('#Modal').modal({show:true});
}

function toSubmitModal(title,content,type){
    $('#Modal').modal({show:true});
    $('#Modal #content').empty().append(content);
    $("#Modal #title").empty().append(title);
    $("#submit").on('click',function(){
        eval('submit'+type)();
    });
}

function showExtent(extent) {
    $("#info").attr("XMin",extent.xmin.toFixed(2) );
    $("#info").attr("YMin",extent.ymin.toFixed(2) );
    $("#info").attr("XMax",extent.xmax.toFixed(2) );
    $("#info").attr("YMax",extent.ymax.toFixed(2) );
}

// tijiao
function submitWaterSource(){
    var dotX=$("#waterSourceName").attr('x');
    var dotY=$("#waterSourceName").attr('y');
    var name=$("#Modal #waterSourceName").val();
    var intro=$("#Modal #waterSourceInfo").val();
    if(!dotX || !dotY){
        alert('请先标注地图坐标 再提交信息');
        return false;
    }

    if(!name || !intro){
        alert('请先填写水源地相关信息 再提交');
        return false;
    }

    var arr = [{ 'x':dotX, 'y':dotY }];
    var _params = {
        'name':name,
        'content':intro,
        'the_geom':JSON.stringify(arr)//array   --   josn
    }

    $.ajax({
        url:'/park/waterSource/add',
        data:_params,
        type:'POST',
        dataType:'json',
        error:function(e){
            console.log(e);
        },
        success:function(data){
            if(data.error){
                alert(data.error);
            }
            if(data.success){
                alert(data.success);
                window.location.reload();
            }
        }
    })
}

function showExtent(extent) {
    $("#info").attr("XMin",extent.xmin.toFixed(2) );
    $("#info").attr("YMin",extent.ymin.toFixed(2) );
    $("#info").attr("XMax",extent.xmax.toFixed(2) );
    $("#info").attr("YMax",extent.ymax.toFixed(2) );
}
// tijiao
function submitTransline(){
    var dots =$("#waterSourceName").attr('polyline');
    var name=$("#Modal #waterSourceName").val();
    var intro=$("#Modal #waterSourceInfo").val();
    if(!dots ){
        alert('请先在地图上标注路线 再提交信息');
        return false;
    }
    if(!name || !intro){
        alert('请先填写运输路线相关信息 再提交');
        return false;
    }
    var _params = {
        'name':name,
        'content':intro,
        'the_geom':JSON.stringify(dots)
    }
    $.ajax({
        url:'/park/chemicalTransport/add',
        data:_params,
        type:'POST',
        dataType:'json',
        error:function(e){
            console.log(e);
        },
        success:function(data){
            if(data.error){
                alert(data.error);
            }
            if(data.success){
                alert(data.success);
                window.location.reload();
            }
        }
    })
}

function loadParkRange(){
    var park_range = eval(park_points);
    var solidColor = [254,236,36],
        fillColor = [102,255,51,255],
        fill_color = [255,255,255,0];
    var rangePolygon = {
        "geometry":{
            "rings":[park_range],
            "spatialReference": { "wkid": 102100 }
        },
        "symbol":{
            "color":fill_color,
            "outline":{
                "color":fillColor,
                "width":4,
                "type":"esriSLS",
                "style":"esriSLSSolid"
            },
            "type":"esriSFS",
            "style":"esriSFSSolid"
        }
    };

    var gra = new esri.Graphic(rangePolygon);
    mymap.graphics.add(gra);
}

// init ...............
function loadWaterPoint(){
    $.get('/park/waterSourceGeo/',function(data){
        var dots = data;
        for(var j=0;j<ids.length;j++){
            for(var i=0;i<dots.length;i++){
              if(ids[j]==dots[i].id){
                    var the_geom = eval(dots[i].the_geom);
                    var pt = new esri.geometry.Point(
                        the_geom[0].x, the_geom[0].y, mymap.spatialReference
                    );

                    var url='/static/images/marker_p.png';
                    var sms = new esri.symbol.PictureMarkerSymbol(url, 24, 24);
                    var attr = {"name":dots[i].name,"content":dots[i].content};
                    var infoTemplate = new esri.InfoTemplate("水源地信息","水源地名称: ${name} <br/> 水源地描述: ${content} ");
                    var graphic = new esri.Graphic(pt,sms,attr,infoTemplate);
                    mymap.graphics.add(graphic);
            }
        }}


    },'json')

}

function loadTransline(){
    $.get('/park/chemicalTransportGeo/',function(data){
        var dots = data;
        for(var j=0;j<ids.length;j++){
            for(var i=0;i<dots.length;i++){
                if(ids[j]==dots[i].id){
                    var _tmpInfo = $("#mapPopHideArea").clone();
                    var _tr = '<tr>';
                    _tr+= '<td>'+ '运输路线名字' +'</td>';
                    _tr+= '<td>'+ dots[i].name +'</td>';
                    _tr+= '</tr>';
                    _tmpInfo.find("table tbody").append(_tr);
                    var _tr = '<tr>';
                    _tr+= '<td>'+ '运输路线详情' +'</td>';
                    _tr+= '<td>'+ dots[i].content +'</td>';
                    _tr+= '</tr>';
                    _tmpInfo.find("table tbody").append(_tr);
                    var _context= _tmpInfo.html();
                    points = JSON.parse(dots[i].the_geom);
                    points = eval(points)
                    var myPolygon = {
                        "geometry":{
                            "paths":[points],
                            "spatialReference": {
                                "wkid": 102100
                            }
                        },
                        "symbol":{
                            "color":[0,187,255,255],
                            "width":3,
                            "type":"esriSLS",
                            "style":"esriSLSSolid"
                        },
                        "infoTemplate":{
                            "title":"化学品运输路线",
                            "content":"<div>"+ _context +"</div>"
                        }
                    };
                    mymap.infoWindow.resize(260,120);
                    var gra = new esri.Graphic(myPolygon);
                    mymap.graphics.add(gra);
                }
            }}
    },'json')
}